# coding:utf-8
from xadmin.plugins.actions import BaseActionView
from django.http import HttpResponse
from xadmin.util import model_format_dict, model_ngettext
from django.contrib.admin.utils import get_deleted_objects
from django.template.response import TemplateResponse
from django.utils.encoding import force_unicode
from django.core.exceptions import PermissionDenied
from django.db import router
from django import forms, VERSION as django_version

ACTION_CHECKBOX_NAME = '_selected_action'


class webPostActions(BaseActionView):
    # 这里需要填写三个属性
    action_name = "webPsot_del_100"  #: 相当于这个 Action 的唯一标示, 尽量用比较针对性的名字
    description = u'自定义删除'  #: 描述, 出现在 Action 菜单中, 可以使用 ``%(verbose_name_plural)s`` 代替 Model 的名字.
    # 这里是是否启用自定义模板
    delete_confirmation_template = None
    delete_selected_confirmation_template = None
    delete_models_batch = True
    model_perm = 'delete'
    icon = 'fa fa-times'

    def do_action(self, queryset):
        print "mypost:"+str(self.request.POST)
        if str(self.request.POST).find("select_across")>0:
            if not self.has_delete_permission():
                raise PermissionDenied
            using = router.db_for_write(self.model)
            if django_version > (2, 0):
                setattr(self.admin_site._registry[self.model], 'has_delete_permission', self.has_delete_permission)

                # Populate deletable_objects, a data structure of all related objects that
                # will also be deleted.

            if django_version > (2, 0):
                deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
                    queryset, self.opts, self.admin_site)
            else:
                deletable_objects, model_count, perms_needed, protected = get_deleted_objects(
                    queryset, self.opts, self.user, self.admin_site, using)

            if len(queryset) == 1:
                objects_name = force_unicode(self.opts.verbose_name)
            else:
                objects_name = force_unicode(self.opts.verbose_name_plural)

            title = "你确定删除吗?"
            context = self.get_context()
            context.update({
                "title": title,
                "objects_name": objects_name,
                "deletable_objects": [deletable_objects],
                'queryset': queryset,
                "perms_lacking": perms_needed,
                "protected": protected,
                "opts": self.opts,
                "app_label": self.app_label,
                'action_checkbox_name': ACTION_CHECKBOX_NAME,
            })
            return TemplateResponse(self.request, self.delete_selected_confirmation_template or
                                    'SipUserDel.html', context,
                                    current_app=self.admin_site.name)
        else:
            for obj in queryset:
                obj.Delete()
